{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入必要的库\n",
    "import numpy as np\n",
    "from sklearn.cluster import KMeans\n",
    "import matplotlib.pyplot as plt\n",
    "import cv2\n",
    "  \n",
    "\n",
    "img = cv2.imread(r'D:\\project7\\data_try\\dog.12457.jpg')\n",
    "img = img.reshape(-1,3)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 应用KMeans聚类\n",
    "# 我们选择k=2，因为我们生成了两个类别的数据\n",
    "kmeans = KMeans(n_clusters=5)\n",
    "kmeans.fit(img)  # 训练模型\n",
    "y_kmeans = kmeans.predict(img)  # 预测每个点的类别\n",
    "\n",
    "# 获取聚类中心\n",
    "centers = kmeans.cluster_centers_\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAgMAAAB3CAYAAACe90OpAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8hTgPZAAAACXBIWXMAAA9hAAAPYQGoP6dpAAACTUlEQVR4nO3YoXFCURRF0ZBJC2iQpCqqoAKGatJAZnB0gQNBHQ/zBS6JyDyx19JXHLnnrsYY4w0AyHqfPQAAmEsMAECcGACAODEAAHFiAADixAAAxIkBAIgTAwAQJwYAIO7jt4fb7fo/d/AH+9Nh9gQW5+tl9gRePG732RNYfB+/Zk9g8bnZ/XjjMwAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOJWY4wxewQAMI/PAADEiQEAiBMDABAnBgAgTgwAQJwYAIA4MQAAcWIAAOLEAADEPQHm/RHnyB1nnwAAAABJRU5ErkJggg==",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# 创建一个 100x100 的全白图像（RGB）\n",
    "image = np.ones((5, 25, 3))  # 3 表示 RGB 通道\n",
    "np.clip(image, 0, 255)\n",
    "for i in range(5):\n",
    "    image[:,i*5:(i+1)*5,:] = centers[i]\n",
    "   \n",
    "np.clip(image, 0, 255)\n",
    "\n",
    "# 确保数据类型为 uint8\n",
    "image = image.astype(np.uint8)\n",
    "\n",
    "# 显示图像\n",
    "plt.imshow(image)\n",
    "plt.axis('off')  # 关闭坐标轴\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0x1f0x1f0x14\n"
     ]
    }
   ],
   "source": [
    "centers = centers.astype(np.uint8)\n",
    "# 使用 np.vectorize 将函数应用到每个元素\n",
    "vectorized_to_hex = np.vectorize(hex)\n",
    "centers_hex = vectorized_to_hex(centers)\n",
    "print(''.join(centers_hex[0]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1f1f14', '7ea489', '397d4b', '1e5d2c', 'd6e0d7']\n"
     ]
    }
   ],
   "source": [
    "\n",
    "centers = centers.astype(np.uint8)\n",
    "# 使用 np.vectorize 将函数应用到每个元素\n",
    "vectorized_to_hex = np.vectorize(hex)\n",
    "centers_hex = vectorized_to_hex(centers)\n",
    "\n",
    "colornums_list = [''.join(centers_hex[i]) for i in range(len(centers_hex))]\n",
    "# 处理 colornums_list\n",
    "for i in range(len(colornums_list)):\n",
    "    colornum = colornums_list[i]\n",
    "    tem_str = ''\n",
    "    for j in range(len(colornum)):\n",
    "        if j % 4 == 2 or j % 4 == 3:\n",
    "            tem_str += str(colornum[j])\n",
    "    colornums_list[i] = tem_str  # 更新 colornums_list\n",
    "\n",
    "print(colornums_list)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1f1f14', '7ea489', '397d4b', '1e5d2c', 'd6e0d7']\n"
     ]
    }
   ],
   "source": [
    "\n",
    "centers = centers.astype(np.uint8)\n",
    "# 使用 np.vectorize 将函数应用到每个元素\n",
    "vectorized_to_hex = np.vectorize(lambda x: f\"{x:02x}\")\n",
    "centers_hex = vectorized_to_hex(centers)\n",
    "\n",
    "colornums_list = [''.join(centers_hex[i]) for i in range(len(centers_hex))]\n",
    "print(colornums_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7868\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7868/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\20814\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\gradio\\analytics.py:106: UserWarning: IMPORTANT: You are using gradio version 4.43.0, however version 4.44.1 is available, please upgrade. \n",
      "--------\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from sklearn.cluster import KMeans\n",
    "import matplotlib.pyplot as plt\n",
    "import cv2\n",
    "import gradio as gr\n",
    "def get_centers(img, k):\n",
    "    \n",
    "    # 将图像转换为二维数组\n",
    "    img = img.reshape(-1,3)\n",
    "\n",
    "    # 应用KMeans聚类\n",
    "    kmeans = KMeans(n_clusters=k)\n",
    "    kmeans.fit(img)  # 训练模型\n",
    "    \n",
    "    # 获取聚类中心\n",
    "    centers = kmeans.cluster_centers_\n",
    "    return centers\n",
    "\n",
    "def create_image(image):\n",
    "    k = 5\n",
    "    centers = get_centers(image, k)\n",
    "    # 创建一个掩模\n",
    "    edge_length = 100\n",
    "    image = np.ones((edge_length, edge_length*k, 3)) * 255 # 3 表示 RGB 通道\n",
    "    np.clip(image, 0, 255)\n",
    "    for i in range(k):\n",
    "        image[:,i*edge_length:(i+1)*edge_length,:] = centers[i]\n",
    "    \n",
    "    np.clip(image, 0, 255)\n",
    "\n",
    "    # 确保数据类型为 uint8\n",
    "    image = image.astype(np.uint8)\n",
    "    return image\n",
    "def get_colornum(image):\n",
    "    k = 5\n",
    "    centers = get_centers(image, k)\n",
    "    centers = centers.astype(np.uint8)\n",
    "    # 使用 np.vectorize 将函数应用到每个元素\n",
    "    vectorized_to_hex = np.vectorize(lambda x: f\"{x:02x}\")\n",
    "    centers_hex = vectorized_to_hex(centers)\n",
    "\n",
    "    colornums_list = [''.join(centers_hex[i]) for i in range(len(centers_hex))]\n",
    "    print(colornums_list)\n",
    "        \n",
    "\n",
    "    # 创建 Gradio 接口\n",
    "    iface = gr.Interface(fn=create_image, inputs=gr.Image(type=\"numpy\"), outputs=gr.Image(type='numpy'))\n",
    "\n",
    "    # 启动 Gradio 应用\n",
    "    iface.launch()\n",
    "    \n",
    "\n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7872\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7872/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\20814\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\gradio\\analytics.py:106: UserWarning: IMPORTANT: You are using gradio version 4.43.0, however version 4.44.1 is available, please upgrade. \n",
      "--------\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from sklearn.cluster import KMeans\n",
    "import gradio as gr\n",
    "\n",
    "def get_centers(img, k):\n",
    "    # 将图像转换为二维数组\n",
    "    img = img.reshape(-1, 3)\n",
    "\n",
    "    # 应用 KMeans 聚类\n",
    "    kmeans = KMeans(n_clusters=k)\n",
    "    kmeans.fit(img)  # 训练模型\n",
    "    \n",
    "    # 获取聚类中心\n",
    "    centers = kmeans.cluster_centers_\n",
    "    return centers\n",
    "\n",
    "def create_image(image):\n",
    "    k = 5\n",
    "    edge_length = 100\n",
    "    centers = get_centers(image, k)\n",
    "    \n",
    "    # 创建一个掩模\n",
    "    output_image = np.ones((100, edge_length*k, 3)) * 255  # 创建全白图像\n",
    "    for i in range(k):\n",
    "        output_image[:, i*edge_length:(i+1)*edge_length, :] = centers[i]  # 每个区域宽度为100\n",
    "    \n",
    "    # 确保数据类型为 uint8\n",
    "    output_image = np.clip(output_image, 0, 255).astype(np.uint8)  # 限制范围并转换类型\n",
    "\n",
    "    # 将 centers 转换为两位十六进制字符串\n",
    "    vectorized_to_hex = np.vectorize(lambda x: f\"{int(x):02x}\")  # 转换为整数后再格式化\n",
    "    centers_hex = vectorized_to_hex(centers)\n",
    "\n",
    "    # 生成 colornums_list\n",
    "    colornums_list = [''.join(centers_hex[i]) for i in range(len(centers_hex))]\n",
    "    colornums_string = \"\\n\".join(colornums_list)  # 每个元素换行\n",
    "\n",
    "    return output_image, colornums_string  # 返回图像和 colornums_string\n",
    "\n",
    "# 创建 Gradio 接口\n",
    "iface = gr.Interface(\n",
    "    fn=create_image,\n",
    "    inputs=gr.Image(type=\"numpy\"),\n",
    "    outputs=[gr.Image(type='numpy'), gr.Textbox(label=\"Color Numbers\")]  # 增加输出框\n",
    ")\n",
    "\n",
    "# 启动 Gradio 应用\n",
    "iface.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7868\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7868/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\20814\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\gradio\\analytics.py:106: UserWarning: IMPORTANT: You are using gradio version 4.43.0, however version 4.44.1 is available, please upgrade. \n",
      "--------\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from sklearn.cluster import KMeans\n",
    "import gradio as gr\n",
    "\n",
    "def process_image(imageNumpy, k, edgeLength):\n",
    "    # 1. 图像预处理\n",
    "    imageArray = imageNumpy.reshape(-1, 3)  # 将图像转换为二维数组\n",
    "\n",
    "    # 2. KMeans聚类\n",
    "    kmeans = KMeans(n_clusters=k, random_state=0).fit(imageArray)\n",
    "\n",
    "    # 3. 获取聚类中心\n",
    "    centers = kmeans.cluster_centers_\n",
    "\n",
    "    # 4. 生成输出图像\n",
    "    outputImage = np.ones((edgeLength, edgeLength * k, 3), dtype=np.uint8) * 255  # 创建全白图像\n",
    "    for i in range(k):\n",
    "        for j in range(k):\n",
    "            outputImage[i*edgeLength:(i+1)*edgeLength, j*edgeLength:(j+1)*edgeLength] = centers[j].astype(np.uint8)\n",
    "\n",
    "    # 5. 数据类型转换\n",
    "    outputImage = outputImage.astype(np.uint8)\n",
    "\n",
    "    # 6. 颜色转换为十六进制\n",
    "    def to_hex(rgb):\n",
    "        return \"#{:02x}{:02x}{:02x}\".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))\n",
    "    centersHex = np.apply_along_axis(to_hex, 1, centers)\n",
    "\n",
    "    # 7. 生成颜色列表\n",
    "    colornumsList = '\\n'.join(centersHex)\n",
    "    colornumsString = colornumsList\n",
    "\n",
    "    # 8. 返回结果\n",
    "    return outputImage, colornumsString\n",
    "\n",
    "def create_gradio_interface():\n",
    "    # 9. Gradio接口\n",
    "    def gradio_func(image, k, edgeLength):\n",
    "        outputImage, colornumsString = process_image(image, k, edgeLength)\n",
    "        return outputImage, colornumsString\n",
    "\n",
    "    iface = gr.Interface(\n",
    "        fn=gradio_func,\n",
    "        inputs=[\n",
    "            gr.Image(label=\"Upload an image\"),\n",
    "            gr.Slider(1, 10, value=5, step=1, label=\"Number of clusters (k)\"),\n",
    "            gr.Slider(50, 250, value=100, step=10, label=\"Edge length of each color block\")\n",
    "        ],\n",
    "        outputs=[\n",
    "            gr.Image(label=\"Clustered image\"),\n",
    "            gr.Textbox(label=\"Color codes in hex\")\n",
    "        ]\n",
    "    )\n",
    "\n",
    "    # 10. 启动应用\n",
    "    iface.launch()\n",
    "\n",
    "# 如果这段代码是作为脚本运行，启动Gradio应用\n",
    "if __name__ == \"__main__\":\n",
    "    create_gradio_interface()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
